package com.jgp.security.interceptor;

import com.jgp.common.annotation.DataPower;
import com.jgp.common.persistence.Model;
import com.jgp.security.config.SecUserAdapter;
import com.jgp.security.pojo.UserInfo;
import com.jgp.sys.utils.SpringContextUtil;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.ArrayUtils;
import org.hibernate.EmptyInterceptor;
import org.hibernate.type.Type;

import java.io.Serializable;
import java.util.Objects;

/**
 * 项目   jgp-cloud-parent
 * 作者   loufei
 * 时间   2019-10-23
 */
@Log4j2
public class DataPermissionInterceptor extends EmptyInterceptor {
    
    @Override
    public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
        DataPower[] powers = entity.getClass().getAnnotationsByType(DataPower.class);
        SecUserAdapter userAdapter = SpringContextUtil.getBean(SecUserAdapter.class);
        Model model = (Model) entity;
        try {
            for (int i = 0; i < propertyNames.length; i++) {
                if(propertyNames[i].equals("rowId")&&powers.length > 0 && Objects.isNull(model.getRowId()) && Objects.nonNull(userAdapter)){
                    String rowId = userAdapter.currentUser().getId();
                    if(Objects.isNull(state[i])){
                        state[i] = rowId;
                    }
                    
                }
                if(Objects.isNull(model.getClientId())&& Objects.nonNull(userAdapter)){
                    UserInfo userInfo = userAdapter.currentUser();
                    String clientId = userInfo.getClientId();
                    String[] excludeModels = userInfo.getExcludeModels();
                    if(!ArrayUtils.contains(excludeModels,model.getClass().getName())&&propertyNames[i].equals("clientId")){
                        if(Objects.isNull(state[i])){
                            state[i] = clientId;
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("插入数据权限标识失败！", e);
            return false;
        }
        return true;
    }
    
    @Override
    public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) {
        return this.onSave( entity,  id, currentState, propertyNames,  types);
    }
}
